import request from '@/utils/request'

// 蓝信开放平台三步走接口的前端封装
// 说明：出于安全，AppId/AppSecret 不应在前端使用，本封装默认调用你后端的代理接口。
// 约定后端路由（可按需在后端适配）：
//  GET /patrol/lanxin/appToken           -> { appToken: string, expiresIn: number }
//  GET /patrol/lanxin/userToken          -> { userToken: string, expiresIn: number, scope?: string, state?: string, staffId?: string }
//  GET /patrol/lanxin/userInfo           -> { staffId: string, name: string, ... }

export interface LanxinAppTokenResp {
  appToken: string
  expiresIn: number
}

export interface LanxinUserTokenResp {
  userToken: string
  expiresIn: number
  scope?: string
  state?: string
  staffId?: string
}

export interface LanxinUserInfo {
  staffId: string
  name?: string
  orgId?: string
  orgName?: string
  avatarId?: string
  avatarUrl?: string
  mobilePhone?: { countryCode?: string; number?: string }
  email?: string
  employeeNumber?: string
  loginName?: string
  externalId?: string
  department?: Array<{ id: string; name: string }>
  [key: string]: any
}

const APP_TOKEN_CACHE_KEY = 'lanxin_app_token_cache'

function nowSeconds(): number {
  return Math.floor(Date.now() / 1000)
}

function getCachedAppToken(): string | null {
  try {
    const raw = localStorage.getItem(APP_TOKEN_CACHE_KEY)
    if (!raw) return null
    const { token, expireAt } = JSON.parse(raw)
    if (!token || !expireAt) return null
    if (nowSeconds() >= expireAt) return null
    return token
  } catch {
    return null
  }
}

function cacheAppToken(token: string, expiresIn: number) {
  const safeExpiresIn = Math.max(0, Number(expiresIn) || 0)
  // 提前1分钟过期，避免边界问题
  const expireAt = nowSeconds() + safeExpiresIn - 60
  localStorage.setItem(APP_TOKEN_CACHE_KEY, JSON.stringify({ token, expireAt }))
}

// 1) 获取应用访问 TOKEN（带缓存）
export async function fetchAppToken(): Promise<string> {
  const cached = getCachedAppToken()
  if (cached) return cached
  const res = await request.get('/patrol/lanxin/appToken')
  const raw: any = res
  const data = (raw && (raw.appToken || raw.data)) ? (raw.appToken ? raw : raw.data) as LanxinAppTokenResp : (raw as LanxinAppTokenResp)
  if (!data?.appToken) throw new Error('获取应用访问TOKEN失败')
  cacheAppToken(data.appToken, Number(data.expiresIn) || 7200)
  return data.appToken
}

// 2) 用 authCode 换人员访问 TOKEN
export async function fetchUserToken(params: { code: string; redirectUri?: string; appToken?: string }): Promise<LanxinUserTokenResp> {
  const query = { code: params.code, redirectUri: params.redirectUri, appToken: params.appToken }
  const res = await request.get('/patrol/lanxin/userToken', { params: query })
  const raw: any = res
  const data = (raw && (raw.userToken || raw.data)) ? (raw.userToken ? raw : raw.data) as LanxinUserTokenResp : (raw as LanxinUserTokenResp)
  if (!data?.userToken) throw new Error('获取人员访问TOKEN失败')
  return data
}

// 3) 获取人员基本信息
export async function fetchUserInfo(params: { userToken: string; appToken?: string }): Promise<LanxinUserInfo> {
  const res = await request.get('/patrol/lanxin/userInfo', { params })
  const raw: any = res
  const data = (raw && (raw.staffId || raw.data)) ? (raw.staffId ? raw : raw.data) as LanxinUserInfo : (raw as LanxinUserInfo)
  if (!data?.staffId) throw new Error('获取人员基本信息失败')
  return data
}

// 4) 获取 JS-SDK 所需 js_api_token（用于前端签名）
export async function fetchJsApiToken(): Promise<string> {
  const res = await request.get('/patrol/lanxin/jsApiToken')
  const raw: any = res
  const token = raw?.jsApiToken || raw?.data?.jsApiToken || raw?.data || raw
  if (!token || typeof token !== 'string') {
    throw new Error('获取 js_api_token 失败')
  }
  return token
}

// 5) 获取 JS-SDK 签名信息（后端计算签名，前端直接使用）
export interface LanxinJsApiSignature {
  appId?: string
  signature: string
  noncestr: string
  timestamp: number
  url: string
}

export async function fetchJsApiSignature(currentUrl: string): Promise<LanxinJsApiSignature> {
  try {
    console.log('🔐 开始获取 JSAPI 签名，URL:', currentUrl)
    console.log('📡 请求路径: /api/lanxin/jsApiSignature')
    const encodedUrl = encodeURIComponent(currentUrl)
    const requestUrl = `/api/lanxin/jsApiSignature?url=${encodedUrl}`
    console.log('📡 完整请求 URL:', requestUrl)
    console.log('📋 原始 URL（用于签名）:', currentUrl)
    const res = await request.get(requestUrl)
    console.log('✅ 后端响应:', res)
    const raw: any = res
    const data = (raw && (raw.signature || raw.data)) 
      ? (raw.signature ? raw : raw.data) as LanxinJsApiSignature 
      : (raw as LanxinJsApiSignature)
    if (!data?.signature || !data?.noncestr || !data?.timestamp) {
      console.error('❌ 签名数据不完整:', data)
      throw new Error('获取 JSAPI 签名信息失败：返回数据不完整')
    }
    console.log('✅ 签名信息获取成功')
    return {
      appId: (data as any).appId,
      signature: data.signature,
      noncestr: data.noncestr,
      timestamp: Number(data.timestamp),
      url: data.url || currentUrl
    }
  } catch (error: any) {
    console.error('❌ 获取 JSAPI 签名失败:', error)
    console.error('错误详情:', {
      message: error?.message,
      code: error?.code,
      response: error?.response,
      config: error?.config
    })
    if (error?.code === 'ERR_NETWORK' || error?.message?.includes('Network Error')) {
      throw new Error(`网络请求失败，请检查：
1. 后端服务是否正常运行
2. 请求路径是否正确: /api/lanxin/jsApiSignature
3. 是否存在 CORS 跨域问题
4. baseUrl 配置是否正确: ${(window as any).APP_CONFIG?.baseUrl || '未配置'}`)
    }
    throw error
  }
}


